<?php

namespace StudyBuddy;

/**
 * Class for working with Bit.ly API
 * to get Short URL
 * Later it may even support more API functions
 * like expand short url back to original
 * or to view some click stats
 * but primaraly we just need to make short URL
 *
 */
class Bitly {

    /**
     * Array of Bit.ly api config
     * - array of !config.ini BITLY section
     *
     * @var array
     */
    protected $config;

    /**
     * Set timeout to 4.5 seconds
     * and a "normal" useragent
     * These params are used by file_get_contents to
     * access Bit.ly api
     * 
     * @var array
     */
    protected $aStreamOptions = array(
        'http' => array('timeout' => 4.5,
            'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.4) Gecko/20091016 Firefox/3.5.4 GTB5')
    );

    /**
     * Constructor
     * 
     * @param mixed $config usually this is array
     * of BITLY section from !config.ini
     */
    public function __construct($config) {
        $this->config = $config;
    }

    /**
     * Get the Short URL using bit.ly api
     * 
     * @todo pass timeout as stream option to be
     * no more than 5 seconds. This is not really necessary
     *
     * @return mixed string | false if no support for bit.ly api
     * or if call to bit.ly api fails
     *
     */
    public function getShortUrl($url) {
        d('input url: ' . $url);
        $tplUrl = 'http://api.bitly.com/v3/shorten?login=%s&apiKey=%s&longUrl=%s&format=json';
        if (!empty($this->config) && !empty($this->config['user']) && !empty($this->config['api_key'])) {
            $context = \stream_context_create($this->aStreamOptions);
            $res = \file_get_contents(sprintf($tplUrl, $this->config['user'], $this->config['api_key'], urlencode($url)), false, $context);
            if (empty($res)) {
                d('did not get data back from bit.ly');
                return false;
            }

            if (false === $a = json_decode($res, true)) {
                d('unable to json_decode data returned by bit.ly ' . $res);
                return false;
            }

            d('bit.ly decoded json data: ' . print_r($a, 1));

            if (!empty($a)
                    && !empty($a['status_code'])
                    && ('200' == $a['status_code'])
                    && !empty($a['data'])
                    && !empty($a['data']['url'])) {
                d('got short url from bit.ly: ' . $a['data']['url']);
                return $a['data']['url'];
            }
        }

        d('no short url from bitly');
        return false;
    }

}
